//index.js
//获取应用实例
import api from '../../utils/api.js'
import moment from '../../lib/moment.js'
const app = getApp()
Page({
  data: {
    currentIndex: 0,
    topicsParams: {
      page: 1,
      tab: '',
      limit: 20
    },
    pageScrollTop: 0,
    fixedNav: false,
    topicsList: [],
    hideArrow: true
  },
  onLoad: function () {
    this.getTopics();
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  //获取主题信息
  getTopics() {
    let page = 'topicsParams.page'
    let tab = 'topicsParams.tab'
    let limit = 'topicsParams.limit'
    if (this.data.currentIndex === 0) {
      this.setData({
        [tab]: ''
      })
    }else if(this.data.currentIndex === 1) {
      this.setData({
        [tab]: 'good'
      })
    } else if (this.data.currentIndex === 2) {
      this.setData({
        [tab]: 'share'
      })
    } else if (this.data.currentIndex === 3) {
      this.setData({
        [tab]: 'ask'
      })
    } else if (this.data.currentIndex === 4) {
      this.setData({
        [tab]: 'job'
      })
    }
    api.getTopics(this.data.topicsParams)
    .then(res => {
      if(res.statusCode === 200) {
        for(let i = 0; i < res.data.data.length; i ++) {
          res.data.data[i].last_reply_at = moment(res.data.data[i].last_reply_at).locale('zh-cn').fromNow()
        }
        this.setData({
          topicsList: this.data.topicsList.concat(res.data.data),
          [page]: this.data.topicsParams.page + 1
        })
      }
    })
    
  },
  getAjax(e) {
    let page = 'topicsParams.page';
    this.setData({
      currentIndex: e.detail,
      [page]: 1,
      topicsList: []
    })
    this.getTopics();
  },
  onPageScroll(e) {
    //判断滚动条高度，实现吸顶式交互
    if(e.scrollTop > 50) {
      if(!this.data.fixedNav)
      this.setData({
        fixedNav: true
      })
    }else {
      if(this.data.fixedNav) {
        this.setData({
          fixedNav: false
        })
      }
    }
    if(e.scrollTop > 1500) {
      if (this.data.hideArrow) {
        this.setData({
          hideArrow: false
        })
      }
    } else {
      if (!this.data.hideArrow) {
        this.setData({
          hideArrow: true
        })
      }
    }
  },
  onReachBottom() {
    this.getTopics();
  },
  onPullDownRefresh() {
    let page = 'topicsParams.page';
    this.setData({
      [page]: 1,
      topicsList: []
    })
    this.onLoad();
  },
  toTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0,
    })
  }
})
